package com.zhdl.network.common_server;

import com.zhdl.network.strategy.common_server.impl.CommonServerSendServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.server.intf.TioServerListener;

@Slf4j
public class CommonTcpServerListener implements TioServerListener {
    CommonServerSendServiceImpl commonServerSendServiceImpl;

    public CommonTcpServerListener(CommonServerSendServiceImpl commonServerSendServiceImpl) {
        this.commonServerSendServiceImpl = commonServerSendServiceImpl;
    }

    @Override
    public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) throws Exception {
        log.debug("{}--->连接服务IP为:{}的连接", channelContext.getClientNode(),
                channelContext.getServerNode().getIp().concat(":").contains(String.valueOf(channelContext.getServerNode().getPort())));
        if (isConnected) {
            commonServerSendServiceImpl.addClientToServer(
                    channelContext.getServerNode().getIp() + ":" + channelContext.getServerNode().getPort(),
                    channelContext.getClientNode().getIp());
        }
    }

    @Override
    public void onAfterDecoded(ChannelContext channelContext, Packet packet, int packetSize) throws Exception {

    }

    @Override
    public void onAfterReceivedBytes(ChannelContext channelContext, int receivedBytes) throws Exception {

    }

    @Override
    public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) throws Exception {

    }

    @Override
    public void onAfterHandled(ChannelContext channelContext, Packet packet, long cost) throws Exception {

    }

    @Override
    public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) throws Exception {
        log.debug("{}--->断开服务IP为:{}的连接", channelContext.getClientNode(),
                channelContext.getServerNode().getIp().concat(":").contains(String.valueOf(channelContext.getServerNode().getPort())));
        commonServerSendServiceImpl.deleteClient(channelContext.getServerNode().getIp() + ":" + channelContext.getServerNode().getPort(),
                channelContext.getClientNode().getIp());
    }

    @Override
    public boolean onHeartbeatTimeout(ChannelContext channelContext, Long aLong, int i) {
        return false;
    }
}
